'use strict';
const EventEmitter = require('events');
const Inquirer = require('inquirer');
const chalk = require('chalk');
const MetalSmith = require('metalsmith');
const path = require('path');
const { render } = require('ejs');
const loadRemoteParset = require('./utils/loadRemoteParset');

module.exports = class extends EventEmitter {
  constructor (name, targetDir) {
    super();
    this.name = name;
    this.targetDir = targetDir;
  };

  async create () {
    const { name, targetDir } = this;
    // 获取模板列表

    this.emit('creation', { event: 'creating' })

    // 拉取模板到本地
    const tmpdir = await loadRemoteParset('direct:git@gitee.com:wangyonggavin/typescript-next.git');

    await new Promise((resolve, reject) => { // 需要用户输入信息
      MetalSmith(__dirname)
        .source(tmpdir)
        .destination(path.resolve(targetDir))
        .use(async (_, metal, done) => {
          const select = await Inquirer.prompt([
            {
              name: 'version',
              message: '请输入项目版本号',
              default: '1.0.0',
            },
            {
              name: 'description',
              message: '请输入项目简介',
              default: 'project created by oce-cli',
            },
            {
              type: "confirm",
              name: "sass",
              message: "是否使用sass",
            },
          ]);
          const meta = metal.metadata(); // 用户填写的结果
          Object.assign(meta, select, { name });
          done();
        })
        .use((files, metal, done) => { // 根据用户输入编写模版
          const meta = metal.metadata();
          Reflect.ownKeys(files).forEach(async (file) => {
            files[file].contents = Buffer.from(await render(files[file].contents.toString(), meta, { async: true }));
          });
          done();
        })
        .build((err) => {
          if (err) {
            reject();
          } else {
            console.log(chalk.green(`
🎉 项目创建成功！

===================================

$ cd ${name}

$ yarn install

$ yarn dev

$ yarn build

$ yarn start

===================================
            `))
            this.emit('creation', { event: 'done' })
            resolve();
          }
        });
    });


  }

}
